//
//  SNUtils.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/4.
//  Copyright © 2016年 stone. All rights reserved.
//

#import "SNUtils.h"
#import "SNMYNavigationController.h"
#import <CommonCrypto/CommonDigest.h>
#import "UIImageView+WebCache.h"
@implementation NSString (Range)

- (NSArray <NSValue *> *)rangesOfString:(NSString *)searchString options:(NSStringCompareOptions)mask serachRange:(NSRange)range {
    
    NSMutableArray *array = [NSMutableArray array];
    
    [self rangeOfString:searchString range:NSMakeRange(0, self.length) array:array options:mask];
    
    return array;
}

- (void)rangeOfString:(NSString *)searchString range:(NSRange)searchRange array:(NSMutableArray *)array options:(NSStringCompareOptions)mask {
    
    NSRange range = [self rangeOfString:searchString options:mask range:searchRange];
    
    if (range.location != NSNotFound) {
        
        [array addObject:[NSValue valueWithRange:range]];
        
        [self rangeOfString:searchString range:NSMakeRange(range.location + range.length, self.length - (range.location + range.length)) array:array options:mask];
    }
}

@end

@implementation SNUtils
+ (instancetype)sharedInstance{
    static id _instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _instance = [[self alloc] init];
    });
    
    return _instance;
}

+ (void)alertViewWithViewController:(UIViewController *)viewController message:(NSString *)message confirmBlock:(void(^)())confirmBlock
{
    NSString * title = @"";
    // NSString * message = message;
    NSString * actionButtonTitle = @"确定";
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * action = [UIAlertAction actionWithTitle:actionButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 确定之后需要 处理的code
        !confirmBlock ?: confirmBlock();
    }];
    
    [alertController addAction:action];
    
    [viewController presentViewController:alertController animated:YES completion:nil];
}
/** 肥料含量 */
+ (NSString *)getFertContentNameWithFertTypes:(NSString *)fertTypes fertContent:(NSString *)fertContent
{
    if(fertTypes.integerValue == 1){
        switch (fertContent.integerValue) {
            case 1:
                return @"氮肥-46%氮";
                
            case 2:
                return @"二胺-18%氮，46%磷";
                
            case 3:
                return @"氯化钾-60%钾";
                
            case 4:
                return @"硫酸钾-50%钾";
                
            default:
                return @"";
                
        }
    }else if(fertTypes.integerValue == 2){
        switch (fertContent.integerValue) {
            case 1:
                return @"15%氮，15%磷，15%钾";
                
            case 2:
                return @"17%氮，17%磷，17%钾";
                
            case 3:
                return @"18%氮，18%磷，18%钾";
                
            case 4:
                return @"其他";
                
            default:
                return @"";
                
        }
    }else if(fertTypes.integerValue == 3){
        switch (fertContent.integerValue) {
            case 1:
                return @"15%氮，15%磷，15%钾";
                
            case 2:
                return @"17%氮，17%磷，17%钾";
                
            case 3:
                return @"18%氮，18%磷，18%钾";
                
            case 4:
                return @"其他";
                
            default:
                return @"";
                
        }
    }else{
        return @"";
    }
}
+ (NSString *)filterAddress:(NSString *)address
{
    NSArray<NSString *> * strings =  [address componentsSeparatedByString:@"|"];
    
    NSMutableString * strM = [NSMutableString string];
    for(int i = 0; i < strings.count; i++) {
        if (i == strings.count - 1) {
            //            NSLog(@"%@",[self foo:strings[i] needNumber:YES]);
            [strM appendString:[self foo:strings[i] needNumber:YES]];
        }else{
            
            //            NSLog(@"%@",[self foo:strings[i] needNumber:NO]);
            [strM appendString:[self foo:strings[i] needNumber:NO]];
        }
    }
    
    return strM;
}
+ (NSString *)foo:(NSString *)str needNumber:(BOOL)needNumber
{
    NSMutableString * strM = [NSMutableString string];
    NSString *searchText = str;
    
    NSString * RegExString;
    if (needNumber) {
        
        RegExString = @"[\u4E00-\u9FFF\\d]+";
    }else{
        RegExString = @"[\u4E00-\u9FFF]+";
        
    }
    
    NSRange range = [searchText rangeOfString:RegExString options:NSRegularExpressionSearch];
    while (range.location != NSNotFound) {
        
        [strM appendString:[NSString stringWithFormat:@"%@ ",[searchText substringWithRange:range]]];
        searchText =  [searchText substringFromIndex:range.location+range.length];
        range = [searchText rangeOfString:RegExString options:NSRegularExpressionSearch];
    }
    //    NSLog(@"%@",strM);
    
    return strM;
}


/** 获取图片 */
+ (void)getImageWithURLString:(NSString *)URLString imageView:(UIImageView *)imageView
{
    if (URLString.length > 0) {
        NSString * urlString = [URLString stringByReplacingOccurrencesOfString:@"//" withString:@"/"];
        urlString = [urlString stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
        
        NSFileManager * manager = [NSFileManager defaultManager];
        NSString * filename = [SNUtils cachedFileNameForKey:urlString];
        if ([manager fileExistsAtPath:kCachePath(filename)]) {
            [imageView sd_setImageWithURL:[NSURL fileURLWithPath:kCachePath(filename)] placeholderImage:kUserIconDefaultImage];
        }else{
            [[ZXHTTPManager sharedManager] GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSData *  _Nullable responseObject) {
                
                NSString * filename = [SNUtils cachedFileNameForKey:urlString];
                
                [responseObject writeToFile:kCachePath(filename) atomically:YES];
                
                // UIImage * image = [UIImage imageWithData:responseObject];
                NSLog(@"kCachePath(filename) = %@",kCachePath(filename));
                [imageView sd_setImageWithURL:[NSURL fileURLWithPath:kCachePath(filename)] placeholderImage:kUserIconDefaultImage];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                NSLog(@"%@",error);
            }];
        }
    }else{
        [imageView sd_setImageWithURL:[NSURL URLWithString:URLString] placeholderImage:kUserIconDefaultImage];
    }
}

/** url md5 */
+ (NSString *)cachedFileNameForKey:(NSString *)key {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
                          r[11], r[12], r[13], r[14], r[15], [[key pathExtension] isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", [key pathExtension]]];
    
    return filename;
}
#pragma mark - 获取UUID
+ (NSString *)calculateUUID {
    CFUUIDRef puuid = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy(NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}
/** 导航条 透明 & 底部黑线去除 */
+ (void)configNavigationStyleWithViewController:(UIViewController *)viewController
{
    [viewController.navigationController.navigationBar setBackgroundImage:[SNUtils imageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
    [viewController.navigationController.navigationBar setShadowImage:[SNUtils imageWithColor:[UIColor clearColor]]];
}
+ (UIView *)testViewWithFrame:(CGRect)frame parentView:(UIView *)parentView
{
    
    UIView * normalView = ({
        UIView * view = [[UIView alloc] init];
        
        view.backgroundColor = [UIColor orangeColor];
        view.frame = frame;
        [parentView addSubview:view];
        
        view;
    });
    return normalView;
}
/** 未知赋值 */
+ (NSString *)fileterWithString:(NSString *)string
{
    if ([string isEqualToString:@""] || string == nil) {
        return @"未知";
    }else{
        return string;
    }
}


+ (CGSize)calculateTextSize:(UILabel *)label width:(CGFloat)width
{
    CGSize size = [[[NSAttributedString alloc] initWithString:label.text attributes:@{NSFontAttributeName : label.font}] boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    return size;
}
+ (void)pushView:(UIView *)pushView pushViewController:(__kindof UIViewController *)pushViewController {
    UIResponder * next = [pushView nextResponder];
    
    while (next != nil) {
        NSLog(@"next = %@",next.class);
        if ([next isKindOfClass:UINavigationController.class] || [next isKindOfClass:SNMYNavigationController.class]) {
            
            //            NSLog(@"找到nav了");
            
            [((UINavigationController *)next) pushViewController:pushViewController animated:YES];
        }
        
        next = [next nextResponder];
    }
}
//sn_note:=========  ============================ stone 🐳 ===========/
/** 16进制(字符串形式) 返回 图片 */
+ (UIImage *)imageWithString:(NSString *)string {
    
    return [self imageWithColor:[self colorWithString:string]];
}
/** 16进制返回颜色 */
+ (UIColor *)colorWithString:(NSString *)string {
    CGFloat alpha = 1.0f;
    NSNumber * red = @0.0;
    NSNumber * green = @0.0;
    NSNumber * blue = @0.0;
    
    NSMutableArray<NSNumber *> * colors = [NSMutableArray arrayWithArray:@[ red, green, blue ]];
    
    unsigned hexComponent;
    NSString * colorString = [string uppercaseString];
//    NSLog(@"%ld", colors.count);
    for (int i = 0; i < colors.count; i++) {
        NSString * substring = [colorString substringWithRange:NSMakeRange(i * 2, 2)];
        
        [[NSScanner scannerWithString:substring] scanHexInt:&hexComponent];
        
        NSNumber * temp = colors[i];
        temp = @(hexComponent / 255.0);
        colors[i] = temp;
    }
    
    return [UIColor colorWithRed:[colors[0] floatValue] green:[colors[1] floatValue] blue:[colors[2] floatValue] alpha:alpha];
}
/** 颜色 返回 图片 */
+ (UIImage *)imageWithColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}
//sn_note:=========  ============================ stone 🐳 ===========/
+ (void)specialLabelWithstring:(NSString *)string keyString:(NSString *)keyString label:(UILabel *)label color:(UIColor *)color {
    if (keyString == nil) {
        return;
    }
    if (string == nil) {
        return;
    }
    NSString * key = [NSString stringWithFormat:@"%@", keyString];
    
    NSMutableArray * arrM = @[].mutableCopy;
    
    [string rangeOfString:key range:NSMakeRange(0, string.length) array:arrM options:kNilOptions];

    NSMutableAttributedString * attribute = [[NSMutableAttributedString alloc] initWithString:string];
    
    for (NSValue * rangeValue in arrM) {
        
        NSRange range = rangeValue.rangeValue;
        
        
        [attribute addAttributes:@{ NSForegroundColorAttributeName : color } range:NSMakeRange(range.location, range.length)];
        
        [label setText:string];
        [label setAttributedText:attribute];
    }
}


@end
